package com.lenovo.smarttraffic.ui.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class CarChargeAdapter extends BaseAdapter {

    private List<Integer> mList;

    private AlertDialog dialog;

    private Context context;
    private SharedPreferences preferences;

    private EditText money_et;

    private int money, threshold_min, threshold_max, chargeable, carId;


    public CarChargeAdapter(Context context, List<Integer> mList) {
        this.mList = mList;
        this.context = context;
        this.preferences = context.getSharedPreferences(Constant.ACCOUNT, Context.MODE_PRIVATE);

        if (money_et == null) {
            money_et = new EditText(context);
            money_et.setHint("请输入余额");
            money_et.setInputType(InputType.TYPE_CLASS_NUMBER);
            money_et.setMaxWidth(4);
        }

        if (dialog == null) {
            dialog = new AlertDialog.Builder(context)
                    .setTitle("充值")
                    .setView(money_et)
                    .setNegativeButton("取消", null)
                    .create();
        }

    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item_car_charge, parent, false);
            holder = new ViewHolder();
            holder.title = convertView.findViewById(R.id.title);
            holder.value = convertView.findViewById(R.id.value);
            holder.charge_btn = convertView.findViewById(R.id.charge_btn);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.title.setText(String.format(Locale.ENGLISH, "第%d号小车", mList.get(position)));

        HttpUtils.post(context, "get_car_account_balance",
                new HttpUtils().setParam("CarId", mList.get(position)).setParam("UserName", MainActivity.userName),
                response -> {
                    Map map = new Gson().fromJson(response.toString(), Map.class);
                    money = (int) Utils.parseDouble(map.get("Balance").toString());
                    holder.value.setText(String.format(Locale.ENGLISH, "余额：%d元", money));
                });

        holder.charge_btn.setOnClickListener(v -> {
            money_et.setText("");

            carId = mList.get(position);

            doFind(holder.value);

            dialog.setMessage(String.format(Locale.ENGLISH, "时间：%s\n账户余额：%s元\n车号：%d", SimpleDateFormat.getDateTimeInstance().format(new Date()), holder.value.getText().toString().split("：")[1].split("元")[0], carId));

            dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定", (dialogInterface, i) -> {
                String moneyStr = money_et.getText().toString();
                int money_input = Utils.parseInt(moneyStr);

                if (moneyStr.isEmpty()) {
                    ToastUtils.showToast(context, "请输入账户余额", Toast.LENGTH_SHORT);
                } else if (money_input < 1) {
                    ToastUtils.showToast(context, "充值金额不能小于1", Toast.LENGTH_SHORT);
                } else if (money_input > 1000) {
                    ToastUtils.showToast(context, "充值金额不能大于1000", Toast.LENGTH_SHORT);
                } else if (money > threshold_max || money < threshold_min) {
                    ToastUtils.showToast(context, "超出阈值，不允许充值", Toast.LENGTH_LONG);
                } else if (money_input > chargeable) {
                    ToastUtils.showToast(context, String.format(Locale.ENGLISH, "充值失败，您本次最多只能充值%d元", chargeable), Toast.LENGTH_LONG);
                } else {
                    HttpUtils.post(context, "set_car_account_recharge",
                            new HttpUtils().setParam("CarId", carId).
                                    setParam("Money", money_input).setParam("UserName", MainActivity.userName),
                            response1 -> {
                                if (Utils.getResult(response1)) {
                                    Toast.makeText(context, "充值成功", Toast.LENGTH_SHORT).show();
                                    doFind(holder.value);
                                } else {
                                    Toast.makeText(context, "充值失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            });


            if (!dialog.isShowing()) {
                dialog.show();

                dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v1 -> {
                    if (!preferences.getBoolean(Constant.CHARGE_CANCEL_TIPS, false)) {
                        TextView textView = new TextView(context);
                        textView.setText("请问你真的要取消充值吗？可能会影响你的正常使用");
                        textView.setTextColor(context.getResources().getColor(R.color.Red));
                        textView.setPadding(70, 70, 70, 70);

                        new AlertDialog.Builder(context)
                                .setTitle("提示")
                                .setView(textView)
                                .setPositiveButton("确定", (dialogInterface1, i1) -> dialog.dismiss())
                                .setNegativeButton("取消", null)
                                .setNeutralButton("不再提示", (dialogInterface12, i12) -> {
                                    dialog.dismiss();
                                    preferences.edit().putBoolean(Constant.CHARGE_CANCEL_TIPS, true).apply();
                                }).show();
                    } else {
                        dialog.dismiss();
                    }
                });
            }

        });

        return convertView;
    }

    private void doFind(TextView textView) {
        Map data = new Gson().fromJson(preferences.getString("car" + carId, null), Map.class);
        if (data != null) {
            threshold_min = Utils.parseInt((String) data.get(Constant.THRESHOLD_MIN));
            threshold_max = Utils.parseInt((String) data.get(Constant.THRESHOLD_MAX));
            chargeable = threshold_max - money;

            HttpUtils.post(context, "get_car_account_balance",
                    new HttpUtils().setParam("CarId", carId).setParam("UserName", MainActivity.userName),
                    response -> {
                        Map responseMap = new Gson().fromJson(response.toString(), Map.class);
                        if (responseMap.get("RESULT").equals("S")) {
                            money = (int) Utils.parseDouble(responseMap.get("Balance").toString());
                            textView.setText(String.format(Locale.ENGLISH, "余额：%d元", money));
                        } else {
                            Toast.makeText(context, "请求错误，可能没有这辆车", Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            textView.setText("查询失败，请设置阈值");
        }

    }

    static class ViewHolder {
        TextView title, value;
        Button charge_btn;
    }
}
